package com.zesionlee.server.config

import com.alibaba.fastjson.JSONObject
import com.zesionlee.server.entity.DBEntity
import com.zesionlee.server.exception.CustomException
import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Component
import org.springframework.util.ResourceUtils
import java.io.File

@Component
class GlobalCurrent {

    @PostConstruct
    fun post() {

        val log = LoggerFactory.getLogger(this::class.java)
        val logo = "\n                     .__              .__                 \n" +
                "________ ____   _____|__| ____   ____ |  |   ____   ____  \n" +
                "\\___   // __ \\ /  ___/  |/  _ \\ /    \\|  | _/ __ \\_/ __ \\ \n" +
                " /    /\\  ___/ \\___ \\|  (  <_> )   |  \\  |_\\  ___/\\  ___/ \n" +
                "/_____ \\\\___  >____  >__|\\____/|___|  /____/\\___  >\\___  >\n" +
                "      \\/    \\/     \\/               \\/          \\/     \\/"

        log.info(logo)
        System.setProperty("pagehelper.banner", false.toString())
        setDataPath()
        setDataSourceFromFile()
    }


    companion object {
        var dataPath: String = ""
        private var dataSource: DataSource? = null
        var dbConfig: DBEntity? = null


        fun setDataPath() {
            dataPath = File(ResourceUtils.getURL("").path).absolutePath + File.separator
            println(dataPath)
        }

        fun setDataSourceFromFile() {
            val dbConfigFile = File(dataPath + "dbConfig.json")
            if (dbConfigFile.exists()) {
                val str = dbConfigFile.readText(Charsets.UTF_8)
                val config = JSONObject.parseObject(str, DBEntity::class.java)
                setDataSource(config)
            }
        }

        fun setDataSource(dbEntity: DBEntity) {
            dbConfig = dbEntity
            dataSource = DataSource(dbEntity)
        }

        fun getDataSource(): DataSource {
            if (dataSource == null) {
                throw CustomException("DataSource is null")
            }
            return dataSource!!
        }


    }


}